package net.ib.mtalk.ui.buddy.item;

import java.util.ArrayList;
import java.util.List;

import net.ib.mntalk.protocol.Common.BuddyInfo;
import net.ib.mntalk.protocol.Common.ContactEntry;
import net.ib.mtalk.R;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.ContactTable;
import net.ib.mtalk.database.helper.BuddyDatabaseHelper;
import net.ib.mtalk.ui.buddy.contact.BuddyContactListActivity;
import net.ib.mtalk.ui.buddy.info.BuddyInfoActivity;
import net.ib.mtalk.ui.buddy.info.BuddyInfoController;
import net.ib.mtalk.ui.dialog.DialogListItem;
import net.ib.mtalk.ui.dialog.DialogMenu2;
import net.ib.mtalk.ui.dialog.DialogMenu3;
import net.ib.mtalk.ui.inbox.InboxController;
import net.ib.mtalk.ui.widget.ActionItem;
import net.ib.mtalk.ui.widget.QuickAction;
import net.ib.mtalk.util.MTalkLogWriter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.text.style.BulletSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

/**
 * 버디의 액션바에 사용할 아이템
 * @author happy2v
 *
 */
public class BuddyActionItem extends ActionItem implements OnClickListener{

	public enum ItemType{
		ONE_TO_ONE(0),
		CALL(1),
		SEND_MESSAGE(2),
		PROFILEVIEW(3),
		INVITE(4),
		FAVORITE(5),
		PHONECONTACT(6);
	
		int type;
		ItemType(int i){
			type = i;
		}
		public int getType(){
			return type;
		}
	}
	
	private Context mContext;
	private ItemType mItemType;
	private int mId;
	private long mReceiverMsb;
	private long mReceiverLsb;
	private BuddyInfo mBuddyInfo;
	private String mDisplayName;
	private int mRaw_id;
	private int mFavorite;
	private int mMode;
	private QuickAction mQuickAction;
	private Dialog mDialog;
	private InboxController mUiController;
	private BuddyInfoController mBuddyInfoController;
	
	public static final int INVITE = 1;
//	Cursor callCursor = null;
	
	private Handler mUiHandler = new Handler();
	
	public BuddyActionItem(Context context, ItemType itemType, int id,
			long receiverMsb, long receiverLsb, BuddyInfo buddyInfo, String displayName, int raw_id, int favorite, QuickAction quickAction){
		this(context, itemType, id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, 0, quickAction, null);
	}

	public BuddyActionItem(Context context, ItemType itemType, int id,
			long receiverMsb, long receiverLsb, BuddyInfo buddyInfo, String displayName, int raw_id, int favorite, int mode, QuickAction quickAction){
		this(context, itemType, id, receiverMsb, receiverLsb, buddyInfo, displayName, raw_id, favorite, mode, quickAction, null);
	}
	
	public BuddyActionItem(Context context, ItemType itemType, int id,
			long receiverMsb, long receiverLsb, BuddyInfo buddyInfo, String displayName, int raw_id, int favorite, int mode, QuickAction quickAction, Dialog dialog){
		mContext = context;
		mItemType = itemType;
		mId = id;
		mReceiverMsb = receiverMsb;
		mReceiverLsb = receiverLsb;
		mBuddyInfo = buddyInfo;
		mDisplayName = displayName;
		mRaw_id = raw_id;
		mFavorite = favorite;
		mMode = mode;
		mQuickAction = quickAction;
		
		mDialog = dialog;
		
		mUiController = new InboxController(mContext, mUiHandler);
		mBuddyInfoController = new BuddyInfoController(mContext, mUiHandler);
			
		setIcon();
		setOnClickListener();
	}
	
	private void setIcon(){
		switch(mItemType){
			case ONE_TO_ONE:
				super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_talk));
				break;
			case CALL:
				super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_call));
				break;
			case SEND_MESSAGE:
				super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_sms));
				break;
			case PROFILEVIEW:
				super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_info));
				break;
			case INVITE:
				super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_invite));
				break;
			case FAVORITE:
				if(mFavorite == 0) super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_add_off));
				else super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_add_on));
				break;
			case PHONECONTACT:
				super.setIcon(mContext.getResources().getDrawable(R.drawable.mn_btn_info));
				break;
		}
	}
	
	/**
	 * ItemType에 맞는 Intent 를 전송한다
	 * @throws Exception 
	 */
	private void setOnClickListener(){
		super.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View view) {
		
		view.setBackgroundResource(R.drawable.quickcontact_slider_btn_pressed);
		try{
			switch(mItemType){
				case ONE_TO_ONE:
					mUiController.startOneToOneChat(mReceiverMsb, mReceiverLsb, mDisplayName);
					break;
				case CALL:
					if(mMode == BuddyContactListActivity.MODE_CONTACT){	// contact에서 케뮤니케이션 채널 띄움.
						Cursor cursor = mContext.getContentResolver().query(ContactTable.CONTENT_URI, null, ContactTable.KEY_CONTACT_PHONE_ID+"=" + mRaw_id, null, null);
						ArrayList<DialogListItem> items = new ArrayList<DialogListItem>();
						try{
							while(cursor.moveToNext()){
								String number = cursor.getString(cursor.getColumnIndex(ContactTable.KEY_CONTACT_NUMBER));
								Log.i("ZOO", number);
								if(cursor.isNull(cursor.getColumnIndex(ContactTable.KEY_BUDDY_UUID_MSB))){
									items.add(new DialogListItem(mContext.getResources(), number, 0));
								} else {
									items.add(new DialogListItem(mContext.getResources(), number, R.drawable.mntalk, R.drawable.mntalk, 0));
								}
							}			
						} finally{
							cursor.close();
						}
						showDialog(mContext, items);
					} else {	// mtalk에서 커뮤니케이션 채널을 띄움.
						String selection = BuddyTable.KEY_BUDDY_UUID_MSB + "=? AND " + BuddyTable.KEY_BUDDY_UUID_LSB + "=?";
						String[] selectionArgs = {String.valueOf(mReceiverMsb), String.valueOf(mReceiverLsb)};
						Cursor cursor = mContext.getContentResolver().query(BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, selection, selectionArgs, null);
						try{
							ArrayList<DialogListItem> items = new ArrayList<DialogListItem>();
							if(cursor.moveToNext()){
								BuddyInfo info = BuddyInfo.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_INFO)));
								List<ContactEntry> list = info.getContactsList();
								for(ContactEntry entry : list){
									if(!items.contains(new DialogListItem(mContext.getResources(), entry.getAccountId().getIdentifier(), 0)))
										items.add(new DialogListItem(mContext.getResources(), entry.getAccountId().getIdentifier(), 0));
								}
							}
							showDialog(mContext, items);
						} finally {
							cursor.close();
						}
					}
					break;
				case SEND_MESSAGE:
					if(mMode == BuddyContactListActivity.MODE_CONTACT){	// contact에서 케뮤니케이션 채널 띄움.
						Cursor cursor = mContext.getContentResolver().query(ContactTable.CONTENT_URI, null, ContactTable.KEY_CONTACT_PHONE_ID+"=" + mRaw_id, null, null);
						ArrayList<DialogListItem> items = new ArrayList<DialogListItem>();
						try{
							while(cursor.moveToNext()){
								String number = cursor.getString(cursor.getColumnIndex(ContactTable.KEY_CONTACT_NUMBER));
								if(cursor.isNull(cursor.getColumnIndex(ContactTable.KEY_BUDDY_UUID_MSB))){
									items.add(new DialogListItem(mContext.getResources(), number, 0));
								} else {
									items.add(new DialogListItem(mContext.getResources(), number, R.drawable.mntalk, R.drawable.mntalk, 0));
								}
							}			
						} finally{
							cursor.close();
						}
						showDialog2(mContext, items);
					} else {	// mtalk에서 커뮤니케이션 채널을 띄움.
						String selection = BuddyTable.KEY_BUDDY_UUID_MSB + "=? AND " + BuddyTable.KEY_BUDDY_UUID_LSB + "=?";
						String[] selectionArgs = {String.valueOf(mReceiverMsb), String.valueOf(mReceiverLsb)};
						Cursor cursor = mContext.getContentResolver().query(BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, selection, selectionArgs, null);
						try{
							if(cursor.moveToFirst()){
								BuddyInfo info = BuddyInfo.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_INFO)));
								List<ContactEntry> list = info.getContactsList();
								ArrayList<DialogListItem> items = new ArrayList<DialogListItem>();
								for(ContactEntry entry : list){
									if(!items.contains(new DialogListItem(mContext.getResources(), entry.getAccountId().getIdentifier(), 0)))
										items.add(new DialogListItem(mContext.getResources(), entry.getAccountId().getIdentifier(), 0));
								}
								showDialog2(mContext, items);
							}
						} finally {
							cursor.close();
						}
					}
					break;
				case PROFILEVIEW:
					Intent intent = new Intent(mContext, BuddyInfoActivity.class);
					intent.putExtra(BuddyTable._ID, mId);
					intent.putExtra(BuddyTable.KEY_BUDDY_UUID_MSB, Long.toString(mReceiverMsb));
					intent.putExtra(BuddyTable.KEY_BUDDY_UUID_LSB, Long.toString(mReceiverLsb));
					intent.putExtra(BuddyTable.KEY_BUDDY_INFO, mBuddyInfo.toByteArray());
					mContext.startActivity(intent);
					break;
				case INVITE:
					if(mMode == BuddyContactListActivity.MODE_CONTACT){	// contact에서 케뮤니케이션 채널 띄움.
						Cursor cursor = mContext.getContentResolver().query(ContactTable.CONTENT_URI, null, ContactTable.KEY_CONTACT_PHONE_ID+"=" + mRaw_id, null, null);
						ArrayList<DialogListItem> items = new ArrayList<DialogListItem>();
						try{
							while(cursor.moveToNext()){
								String number = cursor.getString(cursor.getColumnIndex(ContactTable.KEY_CONTACT_NUMBER));
								if(cursor.isNull(cursor.getColumnIndex(ContactTable.KEY_BUDDY_UUID_MSB))){
									items.add(new DialogListItem(mContext.getResources(), number, 0));
								} else {
									items.add(new DialogListItem(mContext.getResources(), number, R.drawable.mntalk, R.drawable.mntalk, 0));
								}
							}			
						} finally{
							cursor.close();
						}
						showDialog2(mContext, items, INVITE);
					} 
					break;
				case FAVORITE:
					if(mFavorite == 0) mBuddyInfoController.insertFavorite(String.valueOf(mReceiverMsb), String.valueOf(mReceiverLsb));
					else mBuddyInfoController.removeFavorite(String.valueOf(mReceiverMsb), String.valueOf(mReceiverLsb));
					break;
				case PHONECONTACT:
					Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, mRaw_id);
					Intent intent1 = new Intent(Intent.ACTION_VIEW, contactUri);
					mContext.startActivity(intent1);
					break;
			}
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}finally{
			if(mDialog != null) mDialog.dismiss();
			if(mQuickAction != null) mQuickAction.dismiss();
		}
	}

	private void showDialog(Context context, ArrayList<DialogListItem> items) {
		DialogMenu3 dialogMenu = new DialogMenu3(context, items);
		dialogMenu.createDialog().show();
	}

	private void showDialog2(Context context, ArrayList<DialogListItem> items) {
		DialogMenu2 dialogMenu = new DialogMenu2(context, items);
		dialogMenu.createDialog().show();
	}

	private void showDialog2(Context context, ArrayList<DialogListItem> items, int flag) {
		DialogMenu2 dialogMenu = new DialogMenu2(context, items, flag);
		dialogMenu.createDialog().show();
	}
}
